package cz.af.portletExams.backend.rest.converter;

import com.sun.syndication.io.SAXBuilder;
import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;

public abstract class GenericExamModelConverter<T> extends AbstractHttpMessageConverter<T> {

    private static final Logger log = Logger.getLogger(GenericExamModelConverter.class);


    @Override
    protected T readInternal(Class<? extends T> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        SAXBuilder saxBuilder = new SAXBuilder(false);
        Document document = null;

        try {
            document = saxBuilder.build(inputMessage.getBody());
        } catch (JDOMException e) {
            log.error(e);
        }

        final Element rootElement = document.getRootElement();
        return convertToObject(rootElement);
    }

    protected abstract T convertToObject(Element rootElement);

    @Override
    protected boolean canRead(MediaType mediaType) {
        return mediaType != null && "atom+xml".equals(mediaType.getSubtype());
    }

    @Override
    protected void writeInternal(T t, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
    }
}
